import Taro from "@tarojs/taro";
import { uuid } from "./logReport";
import { getLocalToken } from "../userInfo";
import interceptors from "./interceptors";
import { envConfig } from "../config/index.js";
import { Loading } from "../tools/public";

interceptors.forEach((interceptorItem) => Taro.addInterceptor(interceptorItem));

async function request(url, method = "GET", data = {}, options = {}) {
  const header = {
    "i-client-tr": uuid,
    aijiatui: envConfig.companyId,
  };
  options = {
    withToken: true,
    showLoading: true,
    ...options,
  };
  if (options.withToken !== false) header["i-token"] = getLocalToken();
  if (options.showLoading) {
    Loading.show("加载中...", {
      mask: true,
    });
  }

  const res = await Taro.request({ header, url, method, data, options });
  console.log(url, res);
  if (options.showLoading) {
    Loading.hide();
  }

  if (res.code === 0) {
    return res.data;
  }
  return res.msg;
}

// 快捷GET
function get(url, data, options = {}) {
  return request(url, "GET", data, options);
}

// 快捷POST
function post(url, data, options = {}) {
  return request(url, "POST", data, options);
}

export { request, get, post };
